package thread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description: 使用CountDownLatch进行多线程任务
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2024-03-25  20:10
 */
public class ThreadDemo8 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);
        Random random = new Random();
        int time = ( random.nextInt(5) + 1) * 1000;
        for(int i = 0; i < 10; i++) {
            int id = i;
            Thread thread = new Thread(() -> {
                System.out.println("线程" + id + "开始！");
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程" + id + "结束！");
                latch.countDown();
            });
            thread.start();
        }

        latch.await();
        System.out.println("所有线程全部结束！");
    }
}
